package com.botao.controller;

import com.botao.pojo.Classes;
import com.botao.pojo.Page;
import com.botao.pojo.R;
import com.botao.service.ClassesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class ClassesController {
    @Autowired
    ClassesService classesService;

    /**
     * 添加班级
     * @param grade
     * @param zhuanye
     * @param banji
     * @param xueyuan
     * @param response
     * @throws IOException
     */
    @RequestMapping("addGrade")
    public void save(String grade, String zhuanye, String banji, String xueyuan, HttpServletResponse response) throws IOException {
        Classes classes = new Classes(0, grade, zhuanye, banji, xueyuan);
        classesService.save(classes);
        response.sendRedirect("gradeList/1/10");
    }

    /**
     * 班级分页
     * @param currentPage
     * @param pageSize
     * @param model
     * @return
     */
    @RequestMapping("gradeList/{currentPage}/{pageSize}")
    public String list(@PathVariable Long currentPage, @PathVariable Long pageSize, Model model) {
        Page<Classes> classesPage = classesService.listClasses(currentPage, pageSize);
        model.addAttribute("classesPage",classesPage);
        return "gradeList";
    }

    /**
     * 删除班级 异步Ajax
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("deleteGrade")
    public R delete(int id) {
        if(classesService.delete(id)){
            return R.success();
        }else {
            return R.error();
        }
    }

    /**
     * 修改班级页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("modifyGrade/{id}")
    public String modifyGrade(@PathVariable int id, Model model) {
        Classes classes = classesService.getOne(id);
        model.addAttribute("classes", classes);
        return "modifyGrade";
    }

    /**
     * 修改班级
     * @param classes
     * @param response
     * @throws IOException
     */
    @RequestMapping("modifyGradeUpdate")
    public void modifyGradeUpdate(Classes classes, HttpServletResponse response) throws IOException {
        classesService.update(classes);
        response.sendRedirect("gradeList/1/10");
    }

    /**
     * ajax获取班级信息
     * 返回list的json对象
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "getAllClasses")
    public List<Classes> getAllClasses(){
        return classesService.getAllClasses();
    }
}
